<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 500px;
            height: 300px;
            background-color: pink;
            margin: 50px auto 0;
        }
    </style>
    <script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
</head>

<body>
    <!-- 防抖和节流都是性能优化的一种手段 -->
    <!-- 防抖：持续触发不执行，不触发的一段时间后才执行 -->
    <!-- 节流：持续触发也执行，只不过执行的频率变低了 -->
    <!-- 实现一个防抖和节流 -->
    <!-- 不过一般呀，我在实际开发当中更喜欢用 lodash 里面的防抖函数 -->
    <div id="oDiv"></div>
    <script>
        // 需求：鼠标滑过 div 实时获取鼠标相对于盒子的位置，并展示出来

        /* oDiv.onmousemove = function (e) {
          const x = arguments[0].pageX - this.offsetLeft;
          const y = e.pageY - this.offsetTop
          this.innerHTML = `x ${x},y ${y}`
        }; */
        // #1
        /* let bBar = true
        oDiv.onmousemove = function (e) {
          if (bBar) { // #2
            bBar = false // #3
            setTimeout(() => {
              const x = arguments[0].pageX - this.offsetLeft;
              const y = e.pageY - this.offsetTop
              this.innerHTML = `x ${x},y ${y}`
              bBar = true // #4
            }, 1000)
          }
        }; */
        /* const throttle = (callback, time) => {
            let bBar = true
            return function () {
                if (bBar) {
                    bBar = false
                    setTimeout(() => {
                        callback.apply(this, arguments)
                        bBar = true
                    }, time)
                }
            }
        } */
        oDiv.onmousemove = _.throttle(function (e) {
            const x = arguments[0].pageX - this.offsetLeft;
            const y = e.pageY - this.offsetTop
            this.innerHTML = `x ${x},y ${y}`
        }, 1000);
    </script>
</body>

</html>